<script setup>
import { useVModel } from "@vueuse/core";
import { ref, watch, reactive, toRaw, nextTick } from "vue";
import { SearchOutlined, PlayCircleOutlined, PauseCircleOutlined } from "@ant-design/icons-vue";
import { first, find } from "lodash-es";
import request from "@/common/utils/request";
import { watchDebounced, useInfiniteScroll } from "@vueuse/core";
import AudioControl from "./audioControl.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  accountId: {
    type: Number,
    required: true,
  },
  multiple: {//是否多选
    type: Boolean,
    default: false,
  },
  musicList:{
    type: Array,
    default:()=>[]
  },
});
const emit = defineEmits(["update:visible", "selected"]);
const drawerVisible = useVModel(props, "visible", emit);

const audioControlRef = ref();
const playAudioInfo = ref();

const collections = ref([
  {
    id: "6616178533779802884",
    name: "热歌榜",
  },
  {
    id: "866",
    name: "飙升榜",
  },
  {
    id: "6756839411490654983",
    name: "励志",
  },
  {
    id: "6756837234101455624",
    name: "甜蜜物语",
  },
  {
    id: "6756834543140866827",
    name: "欧美",
  },
  {
    id: "1",
    name: "流行",
  },
  {
    id: "6763932535576595208",
    name: "原创",
  },
  {
    id: "20",
    name: "国风",
  },
  {
    id: "6756837098528967437",
    name: "不想长大",
  },
  {
    id: "6740527827793218312",
    name: "翻唱",
  },
  {
    id: "87",
    name: "激萌",
  },
  {
    id: "7047809300823395079",
    name: "说唱",
  },
  {
    id: "88",
    name: "民谣",
  },
  {
    id: "6763060603025099533",
    name: "纯音乐",
  },
]);

const musicList = ref([]);
const hasMore = ref(0);
const loading = ref(false);
const musicListRef = ref();

const query = reactive({
  keyword: "",
  page: 1,
  pageSize: 20,
  collection: first(collections.value).id,
});

watch(drawerVisible, (visible) => {
  if (!visible) {
    query.keyword = "";
    query.page = 1;
    query.collection = first(collections.value).id;
    musicList.value = [];
    hasMore.value = 0;
  } else {
    selectList.value = [...props.musicList]
    getMusicList();
  }
});

const onClose = async () => {
  await pauseAudio();

  drawerVisible.value = false;
  selectList.value = []
};
let selectList = ref([])
const onSelected = (item) => {
  if(props.multiple){
    // lodash 根据id判断是否重复
    let ids = selectList.value.map(t=>t.id)
    if(!ids.includes(item.id)){
       selectList.value.push(item)
    }else{
      let index = selectList.value.findIndex(t=>t.id==item.id)
      selectList.value.splice(index,1)
    }

    // emit("selected", item);
  }else{
    console.log(props.multiple,'props.multiple111');
    emit("selected", item);
    onClose();
  }


};
const ok = ()=>{
  emit("selected", selectList.value);
  onClose();
}
const onCollectionChange = () => {
  onSearch();
};

const onSearch = () => {
  query.page = 1;
  musicList.value = [];
  // hasMore.value = 1;
  getMusicList();
};

watchDebounced(() => query.keyword, onSearch, {
  debounce: 1000,
  maxWait: 5000,
});

const formatTime = (seconds) => {
  var minutes = Math.floor(seconds / 60);
  var remainingSeconds = seconds % 60;

  var formattedMinutes = minutes < 10 ? "0" + minutes : minutes;
  var formattedSeconds =
    remainingSeconds < 10 ? "0" + remainingSeconds : remainingSeconds;

  return formattedMinutes + ":" + formattedSeconds;
};

const getMusicList = async () => {
  if (loading.value) {
    return;
  }

  loading.value = true;
  const { keyword, collection, ...queryParams } = toRaw(query);

  const { data } = await request
    .get("/work_ai", "/org/platform/douyin/media/list", {
      id: props.accountId,
      ...queryParams,
      ...(keyword != ""
        ? {
            keyword,
          }
        : { collection }),
    })
    .catch(() => {
      return {
        data: false,
      };
    });

  if (data) {
    musicList.value = musicList.value.concat(data.musics);
    hasMore.value = data.has_more;
  }
  loading.value = false;
};

async function playAudio(music) {
  await pauseAudio()
  await nextTick()
  playAudioInfo.value = music
}

async function pauseAudio() {
  audioControlRef.value && audioControlRef.value.pauseAudio()
  await nextTick()
  playAudioInfo.value = null
}

useInfiniteScroll(
  musicListRef,
  () => {
    if (hasMore.value) {
      query.page += 1;
      getMusicList();
    }
  },
  { distance: 10 }
);
</script>

<template>
  <a-drawer
    title="选择音乐"
    :visible="drawerVisible"
    :width="450"
    @close="onClose"
    wrapClassName="douyin-music-drawer"
  >
    <div class="flex flex-col h-full" :class="multiple?'multiple-height':''" style="overflow: hidden; gap: 8px">
      <div>
        <div>
          <a-input v-model:value="query.keyword" @keyup.enter="onSearch">
            <template #suffix>
              <SearchOutlined />
            </template>
          </a-input>
        </div>
        <div v-if="!query.keyword">
          <a-tabs
            v-model:activeKey="query.collection"
            @change="onCollectionChange"
          >
            <a-tab-pane
              v-for="collection in collections"
              :key="collection.id"
              :tab="collection.name"
            ></a-tab-pane>
          </a-tabs>
        </div>
      </div>

      <div
        ref="musicListRef"
        class="flex-1"
        style="overflow-y: auto; padding-right: 10px"
      >
        <div
        :class="find(selectList,{id:music.id})?'selected':''"
          class="flex justify-between align-center music-item"
          v-for="music in musicList"
          :key="music.id"
        >
          <div class="flex flex-1" style="gap: 10px; overflow: hidden">
            <div class="flex align-center">
              <PauseCircleOutlined style="font-size: 20px" @click.stop="pauseAudio" v-if="playAudioInfo?.id === music.id"/>
              <PlayCircleOutlined style="font-size: 20px" @click.stop="playAudio(music)" v-else/>
            </div>
            <div class="flex-1" style="overflow: hidden">
              <div
                style="
                  white-space: nowrap;
                  word-break: keep-all;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
              >
                {{ music.title }}
              </div>
              <div style="font-size: 12px; color: #ada5a5">
                {{ music.author }}
              </div>
            </div>
          </div>
          <div style="font-size: 12px; color: #ada5a5">
            {{ formatTime(music.duration) }}
            <a-button
              type="primary"
              class="use-button"
              size="small"
              @click="onSelected(music)"
              >使用</a-button
            >
          </div>
        </div>
        <div class="music-loading" v-if="loading">
          <a-spin :spinning="loading" tip="正在加载列表..."></a-spin>
        </div>
      </div>
    </div>
    <div
      v-if="multiple"
      :style="{
        position: 'absolute',
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e8e8e8',
        padding: '10px 16px',
        textAlign: 'right',
        left: 0,
        background: '#fff',
        borderRadius: '0 0 4px 4px',
      }"
    >
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button type="primary" @click="ok">确定</a-button>
    </div>

    <AudioControl
      v-if="playAudioInfo"
      ref="audioControlRef"
      :url="playAudioInfo.play_url"
      :duration="playAudioInfo.duration"
      :info="{
        name: playAudioInfo.title,
        author: playAudioInfo.author
      }"
      :autoplay="true"
    />
  </a-drawer>
</template>

<style lang="less" scoped>
.music-item {
  padding: 10px;
  cursor: pointer;
  gap: 6px;

  &:hover {
    background-color: #ebebeb;

    .use-button {
      display: inline-block;
    }
  }

  .use-button {
    margin-left: 8px;
    border-radius: 5px;
    display: none;
  }
}

.music-loading {
  text-align: center;

  .ant-spin {
    display: flex;
    justify-content: center;
    gap: 8px;
    font-size: 12px;
  }
}
</style>

<style lang="less">
.douyin-music-drawer {
  .ant-drawer-wrapper-body {
    display: flex;
    flex-direction: column;

    .ant-drawer-body {
      overflow: hidden;
      flex: 1;

      .ant-tabs-bar {
        margin-bottom: 0px;
      }
    }
  }

  .ss-drawer-body {
    position: relative;
  }
}
.multiple-height{
  height: calc(100% - 32px);
}
.selected{
 color: var(--ss-primary-color)!important;
}
</style>
